package com.xiaoximen;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EditTimeListActivity extends Activity {
	
	private static final int REQ_SET_DATE = 1;
	
	static final String KEY_YEAR = "year";
	static final String KEY_MONTH = "month";
	static final String KEY_DAY = "day";
	static final String KEY_WEEKDAY = "weekday";
	
	static final String KEY_START_TIME = "start_time";
	static final String KEY_END_TIME = "end_time";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_time_list);
		
		init();
	}
	
	private void init() {
		findViewById(R.id.edit_time_list_add).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final Time time = new Time();
				time.setToNow();
				DatePickerDialog picker = new DatePickerDialog(EditTimeListActivity.this,
						new DatePickerDialog.OnDateSetListener() {
					
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						Intent intent = new Intent(getApplicationContext(), 
								TimePickerActivity.class);
						intent.putExtra(KEY_YEAR, year);
						intent.putExtra(KEY_MONTH, (monthOfYear+1));
						intent.putExtra(KEY_DAY, dayOfMonth);
						time.set(dayOfMonth, monthOfYear, year);
						intent.putExtra(KEY_WEEKDAY, getResources().getStringArray(
								R.array.weekday)[time.weekDay]);
						startActivityForResult(intent, REQ_SET_DATE);
					}
				}, time.year, time.month, time.monthDay);
				picker.setTitle(R.string.pick_date);
				picker.show();
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case REQ_SET_DATE:
				Time start = new Time();
				start.set(data.getLongExtra(KEY_START_TIME, System.currentTimeMillis()));
				Time end = new Time();
				end.set(data.getLongExtra(KEY_END_TIME, System.currentTimeMillis()));
				String text = start.year + getString(R.string.year)
						+ (start.month+1) + getString(R.string.month)
						+ start.monthDay + getString(R.string.day) + " "
						+ getResources().getStringArray(R.array.weekday)[start.weekDay]
						+ "\n"+ start.hour + ":00 ~ " + end.hour + ":00";
				View v = LayoutInflater.from(getApplicationContext()).inflate(
						R.layout.time_list_item, null);
				((TextView) v.findViewById(R.id.time_list_item)).setText(text);
				((LinearLayout) findViewById(R.id.edit_event_time_list_layout))
						.addView(v);
				break;
			}
		}
	}
}
